﻿using System;
using System.Security.Cryptography;
using System.Text;
using System.Web.Mvc;

namespace Promike.site.Helpers
{
    public static class UrlExtentions
    {
        public static string Gravatar(this UrlHelper url, string emailAddress)
        {
            const string baseUrl = "http://www.gravatar.com/avatar/{0}";
            return String.Format(baseUrl, Md5Hash(emailAddress.ToLower()));
        }

        public static string Gravatar(this UrlHelper url, string emailAddress, int size)
        {
            const string baseUrl = "http://www.gravatar.com/avatar/{0}?s={1}";
            return String.Format(baseUrl, Md5Hash(emailAddress.ToLower()), size);
        }

        private static string Md5Hash(string input)
            {
                var hash = new StringBuilder();
                var md5Provider = new MD5CryptoServiceProvider();
                var bytes = md5Provider.ComputeHash(new UTF8Encoding().GetBytes(input));

                for (var i = 0; i < bytes.Length; i++)
                {
                    hash.Append(bytes[i].ToString("x2"));
                }
                return hash.ToString();
            }
    }
}